package com.blog.utility;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;

import com.blog.domain.User;
import com.blog.service.BlogService;
import com.blog.service.MenuTree;

@SuppressWarnings("serial")
public class BlogFilter extends HttpServlet implements Filter {
	
	// Handle the passed-in FilterConfig
	public void init(FilterConfig filterConfig) {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws java.io.IOException,
			ServletException {
		HttpServletRequest hrequest = (HttpServletRequest) request;
		HttpSession session = hrequest.getSession();
		ApplicationContext app = CommonApplicationContextUtil.getContext();
	
		if (hrequest.getParameter("loginPage")!=null) {
			//登陆页面
			String mailId = hrequest.getParameter("userId");
			String password = hrequest.getParameter("password");
			if(mailId==null ||mailId.equals("")||password==null ||password.equals("")){
				hrequest.setAttribute("msg", "登陆名和密码不能为空");
				hrequest.getRequestDispatcher("/index.jsp").forward(request,
						response);
				return;
			}
			BlogService blogService=(BlogService) app.getBean("BlogService");
			User user = blogService.queryUser(mailId, password);
			if (user == null) {
				hrequest.setAttribute("msg", "登陆名或者密码错误,请重新登陆");
				hrequest.getRequestDispatcher("/index.jsp").forward(request,
						response);
				return;
			}else{
				session.setAttribute("user", user);			
			}
			
		}
		if(session.getAttribute("menuTree")==null){
			MenuTree menuTree=(MenuTree) app.getBean("menuTree");
			menuTree.setAuthMenuTree();
			session.setAttribute("menuTree", menuTree);
		}
		filterChain.doFilter(request, response);
		
	}

	// Clean up resources
	public void destroy() {
	}
}
